<template>
  <vxe-modal
    :title="$t('common.action.reset_pwd', '重置密码')"
    v-model="show"
    :loading="loading"
    :mask="false"
    :lock-view="false"
    width="600px"
    height="300px"
    destroy-on-close
    show-zoom
    remember
    resize
    show-footer
  >
    <el-form
      ref="refForm"
      :model="formData"
      :rules="formRules"
      label-width="120px"
    >
      <!-- 新密码 -->
      <el-form-item
        :label="$t('menu.profile.field.new_password', '新密码')"
        prop="newPassword"
      >
        <el-input
          v-model="formData.newPassword"
          type="password"
          show-password
          :placeholder="$p('menu.profile.field.new_password', '新密码')"
        />
      </el-form-item>

      <!-- 确认新密码 -->
      <el-form-item
        :label="$t('menu.profile.field.confirm_password', '确认密码')"
        prop="confirmPassword"
      >
        <el-input
          v-model="formData.confirmPassword"
          type="password"
          show-password
          :placeholder="$p('menu.profile.field.confirm_password', '确认密码')"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button type="warning" @click="handleCancel">
        {{ $t('common.action.cancel', '取消') }}
      </el-button>
      <el-button type="info" @click="handleReset">
        {{ $t('common.action.reset', '重置') }}
      </el-button>
      <el-button type="primary" @click="handleSubmit" :disabled="loading">
        {{ $t('common.action.confirm', '确定') }}
      </el-button>
    </template>
  </vxe-modal>
</template>

<script setup>
import { smartTranslate as $t, transPlaceholder as $p } from '@/lang';

defineOptions({
  name: 'ResetPassword',
  inheritAttrs: false,
});

const props = defineProps({
  api: {
    type: Object,
    required: true,
    validator: (value) => {
      return typeof value.resetPassword === 'function';
    },
  },
});

const emit = defineEmits(['reload']);

// 响应式数据
const loading = ref(false);
const show = ref(false);
const refForm = ref();
const formData = ref({
  id: null,
  newPassword: null,
  confirmPassword: null,
});

// 密码强度验证函数
const validatePasswordStrength = (rule, value, callback) => {
  if (!value) {
    callback(
      new Error($t('menu.profile.validate.new_password', '请输入新密码')),
    );
    return;
  }

  // 至少6位
  if (value.length < 6) {
    callback(
      new Error(
        $t('common.message.validate.min', {
          default: '{field}至少需要{min}个字符',
          params: {
            field: $t('menu.profile.field.new_password', '新密码'),
            min: 6,
          },
        }),
      ),
    );
    return;
  }
  callback();
};

const validatePasswordMatch = (rule, value, callback) => {
  if (!value) {
    callback(
      new Error($t('menu.profile.validate.confirm_password', '请输入确认密码')),
    );
  } else if (value !== formData.value.newPassword) {
    callback(
      new Error($t('menu.profile.validate.not_match', '两次输入的密码不一致')),
    );
  } else {
    callback();
  }
};

// 表单验证规则
const formRules = {
  newPassword: [
    {
      required: true,
      validator: validatePasswordStrength,
      trigger: 'blur',
    },
  ],
  confirmPassword: [
    {
      required: true,
      validator: validatePasswordMatch,
      trigger: 'blur',
    },
  ],
};

// 重置表单
const resetForm = () => {
  refForm.value?.resetFields();
  Object.assign(formData.value, {
    id: null,
    newPassword: null,
    confirmPassword: null,
  });
};

// 提交处理
const handleSubmit = async () => {
  try {
    await refForm.value.validate();
    loading.value = true;
    const postData = {
      id: formData.value.id,
      password: formData.value.newPassword,
    };
    console.log('Reset Password Data:', postData);
    await props.api.resetPassword(postData);
    resetForm();
    show.value = false;
    emit('reload');
  } catch (error) {
    console.error('Error in reset password operation:', error);
  } finally {
    loading.value = false;
  }
};

// 取消处理
const handleCancel = () => {
  resetForm();
  show.value = false;
};

// 重置处理
const handleReset = () => {
  resetForm();
};

// 显示模态框
const showModal = (id) => {
  show.value = true;
  nextTick(() => {
    resetForm();
    if (id) {
      formData.value.id = id;
    }
  });
};

defineExpose({
  show: showModal,
});
</script>

<style lang="scss" scoped>
.form-section {
  margin: 5px;
  border: 1px solid #dcdfe6;
  padding: 5px;
  border-radius: 4px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-input__wrapper) {
  transition: all 0.3s ease;
}

:deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px var(--el-color-primary) inset;
}
</style>
